// WebSocket服务
import { ElNotification } from 'element-plus';
import { getAuthToken, getUserId } from '../utils/authUtils'

class WebSocketService {
  constructor() {
    console.log('WebSocketService 初始化')
    this.socket = null
    this.isConnecting = false
    this.isConnected = false
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectDelay = 3000
    this.notificationHandlers = []
    this.messageHandlers = []
    this.heartbeatInterval = null
    this.lastHeartbeatResponse = 0
    this.debugMode = true // 开启调试模式
    
    console.log('WebSocketService: 构造函数执行完成，准备自动连接')
    this.autoConnect()
  }

  // 自动连接websocket
  autoConnect() {
    console.log('WebSocketService: 尝试自动连接')
    const token = getAuthToken()
    const userId = getUserId()
    
    console.log('WebSocketService: 自动连接检查 - 令牌状态:', token ? '存在' : '不存在', '用户ID:', userId)
    
    if (!userId) {
      console.warn('WebSocketService: 用户未登录，不进行连接')
      return
    }
    
    console.log(`WebSocketService: 用户已登录(ID=${userId})，开始连接`)
    this.connect(userId)
  }

  // 连接WebSocket
  connect(userId) {
    if (this.isConnecting) {
      console.warn('WebSocketService: 已经在连接中，不重复连接')
      return
    }
    
    if (this.isConnected) {
      console.warn('WebSocketService: 已经连接成功，不重复连接')
      return
    }

    this.isConnecting = true
    console.log(`WebSocketService: 尝试连接WebSocket, userId=${userId}, 类型: ${typeof userId}`)

    try {
      // 开发环境使用ws，生产环境使用wss
      const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
      
      // 强制使用后端服务器地址，而不是当前窗口的主机和端口
      const host = 'localhost'
      const port = '8080'
      
      // 使用与后端配置匹配的WebSocket路径
      // 确保路径与WebSocketConfig.java中的配置一致
      const wsUrl = `${protocol}://${host}:${port}/ws/notifications/${userId}`
      console.log(`WebSocketService: 连接到 ${wsUrl}`)
      
      // 添加更多调试信息
      console.group('WebSocket连接详情')
      console.log('协议:', protocol)
      console.log('主机:', host)
      console.log('端口:', port)
      console.log('用户ID:', userId, '(类型:', typeof userId, ')')
      console.log('完整URL:', wsUrl)
      console.log('浏览器在线状态:', navigator.onLine ? '在线' : '离线')
      console.groupEnd()

      this.socket = new WebSocket(wsUrl)

      this.socket.onopen = () => {
        console.log('%cWebSocketService: 连接成功!', 'color: green; font-weight: bold')
        this.isConnected = true
        this.isConnecting = false
        this.reconnectAttempts = 0
        
        // 调试连接状态
        console.log('WebSocketService: 连接状态:', this.socket.readyState)
        
        // 发送自我标识消息
        this.sendIdentity(userId)
        
        // 开始发送心跳包
        this.startHeartbeat()
      }

      this.socket.onmessage = (event) => {
        console.log('%cWebSocketService: 收到消息', 'color: blue; font-weight: bold', event.data)
        
        try {
          const message = JSON.parse(event.data)
          console.log('WebSocketService: 解析后的消息数据:', message)
          
          if (message.type === 'HEARTBEAT') {
            this.lastHeartbeatResponse = Date.now()
            console.log(`WebSocketService: 收到心跳响应 (${new Date(this.lastHeartbeatResponse).toLocaleTimeString()})`)
            return
          }
          
          if (message.type === 'NOTIFICATION') {
            console.log('WebSocketService: 处理通知消息类型:', message.notificationType)
            this.handleNotification(message)
          } else if (message.type === 'MESSAGE') {
            console.log('WebSocketService: 处理聊天消息')
            this.handleMessage(message)
          } else if (message.type === 'SYSTEM') {
            console.log('WebSocketService: 处理系统消息')
            // 显示系统消息
            ElNotification({
              title: '系统消息',
              message: message.message || '收到系统消息',
              type: 'info',
              duration: 3000
            })
          } else if (message.type === 'CONFIRMATION') {
            console.log('WebSocketService: 收到确认消息')
          } else if (message.type === 'ERROR') {
            console.error('WebSocketService: 收到错误消息', message)
            ElNotification({
              title: 'WebSocket错误',
              message: message.message || '服务器返回错误',
              type: 'error',
              duration: 5000
            })
          } else {
            console.warn('WebSocketService: 未知消息类型', message.type, message)
          }
        } catch (error) {
          console.error('WebSocketService: 消息解析错误', error, '原始数据:', event.data)
          try {
            // 尝试显示错误信息
            ElNotification({
              title: 'WebSocket错误',
              message: `消息解析失败: ${error.message}`,
              type: 'error',
              duration: 3000
            })
          } catch (e) {
            console.error('无法显示通知', e)
          }
        }
      }

      this.socket.onclose = (event) => {
        const reason = event.reason ? ` 原因: ${event.reason}` : ''
        const code = event.code ? ` 代码: ${event.code}` : ''
        console.log(`%cWebSocketService: 连接关闭${code}${reason}`, 'color: orange; font-weight: bold')
        
        this.isConnected = false
        this.isConnecting = false
        
        if (this.heartbeatInterval) {
          clearInterval(this.heartbeatInterval)
          this.heartbeatInterval = null
        }
        
        // 自动重连
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          const delay = this.reconnectDelay * Math.pow(1.5, this.reconnectAttempts)
          console.log(`WebSocketService: 计划在 ${delay}ms 后尝试重连 (${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`)
          
          setTimeout(() => {
            this.reconnectAttempts++
            console.log(`WebSocketService: 开始第 ${this.reconnectAttempts} 次重连尝试`)
            this.connect(userId)
          }, delay)
        } else {
          console.error('WebSocketService: 重连次数达到上限，停止重连')
          try {
            ElNotification({
              title: 'WebSocket连接失败',
              message: '无法连接到通知服务，请刷新页面重试',
              type: 'error',
              duration: 0
            })
          } catch (e) {
            console.error('无法显示通知', e)
          }
        }
      }

      this.socket.onerror = (error) => {
        console.error('WebSocketService: 连接错误', error)
        
        // 确保在错误发生时重置连接状态
        this.isConnecting = false
        
        // 如果连接尚未关闭，主动关闭它
        if (this.socket && (this.socket.readyState === WebSocket.CONNECTING || 
            this.socket.readyState === WebSocket.OPEN)) {
          console.log('WebSocketService: 因错误主动关闭连接');
          try {
            this.socket.close();
          } catch (e) {
            console.error('WebSocketService: 关闭连接时出错', e);
          }
        }
        
        // 检查网络连接
        if (navigator.onLine) {
          console.log('WebSocketService: 网络连接正常，可能是服务器问题')
        } else {
          console.log('WebSocketService: 网络连接已断开')
        }
      }
    } catch (error) {
      console.error('WebSocketService: 创建WebSocket连接发生错误', error)
      this.isConnecting = false
      
      // 显示错误通知
      try {
        ElNotification({
          title: 'WebSocket连接失败',
          message: `无法连接到通知服务: ${error.message}`,
          type: 'error',
          duration: 5000
        })
      } catch (e) {
        console.error('无法显示通知', e)
      }
    }
  }
  
  // 发送身份识别消息
  sendIdentity(userId) {
    try {
      const identity = {
        type: 'IDENTITY',
        userId: userId,
        timestamp: Date.now()
      }
      console.log('WebSocketService: 发送身份识别消息:', identity)
      this.send(identity)
    } catch (error) {
      console.error('WebSocketService: 发送身份识别消息失败', error)
    }
  }

  // 发送心跳包，保持连接活跃
  startHeartbeat() {
    console.log('WebSocketService: 开始发送心跳包')
    this.lastHeartbeatResponse = Date.now()
    
    if (this.heartbeatInterval) {
      console.log('WebSocketService: 清除旧的心跳定时器')
      clearInterval(this.heartbeatInterval)
    }
    
    this.heartbeatInterval = setInterval(() => {
      if (this.isConnected && this.socket) {
        const now = Date.now()
        const lastResponseTime = now - this.lastHeartbeatResponse
        
        if (lastResponseTime > 70000) { // 70秒没收到响应
          console.warn(`WebSocketService: 心跳响应超时 (${Math.round(lastResponseTime/1000)}秒)，关闭连接并重连`)
          this.socket.close()
          return
        }
        
        // 确保心跳包格式与后端预期一致
        const heartbeat = {
          type: 'HEARTBEAT',
          timestamp: now
        }
        console.log(`WebSocketService: 发送心跳包 (${new Date(now).toLocaleTimeString()})`)
        const success = this.send(heartbeat)
        if (!success) {
          console.error('WebSocketService: 心跳包发送失败，尝试重新连接')
          this.socket.close()
        }
      } else {
        console.warn('WebSocketService: WebSocket未连接，停止心跳')
        if (this.heartbeatInterval) {
          clearInterval(this.heartbeatInterval)
          this.heartbeatInterval = null
        }
      }
    }, 30000) // 每30秒发送一次心跳
  }

  // 发送消息到服务器
  send(message) {
    if (!this.isConnected || !this.socket) {
      console.error('WebSocketService: WebSocket未连接，无法发送消息')
      return false
    }
    
    try {
      const messageStr = typeof message === 'string' ? message : JSON.stringify(message)
      this.socket.send(messageStr)
      
      if (this.debugMode && message.type !== 'HEARTBEAT') {
        console.log('WebSocketService: 成功发送消息', message)
      }
      
      return true
    } catch (error) {
      console.error('WebSocketService: 发送消息失败', error, message)
      return false
    }
  }

  // 断开WebSocket连接
  disconnect() {
    console.log('WebSocketService: 主动断开连接')
    
    // 清除心跳定时器
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
      console.log('WebSocketService: 清除心跳定时器')
    }
    
    // 重置状态标志
    this.isConnecting = false
    this.isConnected = false
    this.reconnectAttempts = 0
    
    // 关闭连接
    if (this.socket) {
      console.log('WebSocketService: 关闭WebSocket连接')
      
      try {
        // 只有在连接开启状态才需要关闭
        if (this.socket.readyState === WebSocket.OPEN || 
            this.socket.readyState === WebSocket.CONNECTING) {
          this.socket.close(1000, '用户主动断开')
        }
      } catch (e) {
        console.error('WebSocketService: 关闭连接时出错', e)
      }
      
      this.socket = null
    }
  }

  // 处理通知消息
  handleNotification(message) {
    console.log('%cWebSocketService: 处理通知消息', 'color: purple; font-weight: bold', message)
    
    // 调试显示当前注册的处理器数量
    console.log(`WebSocketService: 当前有 ${this.notificationHandlers.length} 个通知处理器`)
    
    if (this.notificationHandlers.length === 0) {
      console.warn('WebSocketService: 没有注册通知处理器，通知可能不会显示')
    }
    
    this.notificationHandlers.forEach((handler, index) => {
      try {
        console.log(`WebSocketService: 调用通知处理器 #${index + 1}`)
        handler(message)
      } catch (error) {
        console.error(`WebSocketService: 处理器 #${index + 1} 执行错误`, error)
      }
    })
  }

  // 处理聊天消息
  handleMessage(message) {
    console.log('%cWebSocketService: 处理聊天消息', 'color: green; font-weight: bold', message)
    
    // 调试显示当前注册的处理器数量
    console.log(`WebSocketService: 当前有 ${this.messageHandlers.length} 个消息处理器`)
    
    if (this.messageHandlers.length === 0) {
      console.warn('WebSocketService: 没有注册消息处理器，消息可能不会显示')
    }
    
    this.messageHandlers.forEach((handler, index) => {
      try {
        console.log(`WebSocketService: 调用消息处理器 #${index + 1}`)
        handler(message)
      } catch (error) {
        console.error(`WebSocketService: 消息处理器 #${index + 1} 执行错误`, error)
      }
    })
  }

  // 添加通知处理函数
  addNotificationHandler(handler) {
    if (typeof handler !== 'function') {
      console.error('WebSocketService: 添加的处理器不是函数', handler)
      return false
    }
    
    console.log('WebSocketService: 添加通知处理器')
    this.notificationHandlers.push(handler)
    console.log(`WebSocketService: 当前有 ${this.notificationHandlers.length} 个通知处理器`)
    return true
  }

  // 移除通知处理函数
  removeNotificationHandler(handler) {
    console.log('WebSocketService: 尝试移除通知处理器')
    const index = this.notificationHandlers.indexOf(handler)
    if (index !== -1) {
      this.notificationHandlers.splice(index, 1)
      console.log(`WebSocketService: 成功移除通知处理器，当前剩余 ${this.notificationHandlers.length} 个`)
      return true
    }
    console.log('WebSocketService: 未找到要移除的通知处理器')
    return false
  }

  // 添加消息处理函数
  addMessageHandler(handler) {
    if (typeof handler !== 'function') {
      console.error('WebSocketService: 添加的消息处理器不是函数', handler)
      return false
    }
    
    console.log('WebSocketService: 添加消息处理器')
    this.messageHandlers.push(handler)
    console.log(`WebSocketService: 当前有 ${this.messageHandlers.length} 个消息处理器`)
    return true
  }

  // 移除消息处理函数
  removeMessageHandler(handler) {
    console.log('WebSocketService: 尝试移除消息处理器')
    const index = this.messageHandlers.indexOf(handler)
    if (index !== -1) {
      this.messageHandlers.splice(index, 1)
      console.log(`WebSocketService: 成功移除消息处理器，当前剩余 ${this.messageHandlers.length} 个`)
      return true
    }
    console.log('WebSocketService: 未找到要移除的消息处理器')
    return false
  }
  
  // 获取连接状态
  getConnectionStatus() {
    return {
      isConnected: this.isConnected,
      isConnecting: this.isConnecting,
      socketState: this.socket ? this.socket.readyState : -1,
      reconnectAttempts: this.reconnectAttempts,
      lastHeartbeat: this.lastHeartbeatResponse ? new Date(this.lastHeartbeatResponse).toLocaleString() : '无'
    }
  }
}

// 创建单例
const websocketService = new WebSocketService()
export default websocketService 